package com.jkdl.springboot.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jkdl.springboot.common.util.DateTools;
import com.jkdl.springboot.common.util.JsonResult;
import com.jkdl.springboot.common.util.Md5Util;
import com.jkdl.springboot.common.util.WxUtil.HttpUtil;
import com.jkdl.springboot.common.util.WxUtil.WxConfigUtil;
import com.jkdl.springboot.common.util.WxUtil.WxunionidUtil;
import com.jkdl.springboot.dao.*;
import com.jkdl.springboot.domain.*;
import com.jkdl.springboot.entity.*;
import com.jkdl.springboot.exception.BusinessException;
import com.jkdl.springboot.service.SystemUserRoleAuthService;
import com.jkdl.springboot.service.UCompanyService;
import com.vdurmont.emoji.EmojiParser;
import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.IOException;
import java.util.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;


import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.BeanUtils;

@Slf4j
@Service
public class UCompanyServiceImpl implements UCompanyService {

    @Autowired
    private SystemUserRoleAuthService systemUserRoleAuthService;

    @Autowired
    private UCompanyMapper uCompanyMapper;

    @Autowired
    private USersMapper uSersMapper;


    @Autowired
    private OdrOrderMapper odrOrderMapper;

    @Autowired
    private PdProductsMapper pdProductsMapper;

    @Autowired
    private UCompanyUserMapper uCompanyUserMapper;

    @Override
    public Long add(UCompany uCompany) throws Exception {
        return null;
    }

    @Override
    public List<UCompany> selectAllUCompanyList(UCompanyQueryVo uCompanyQueryVo) {

        List<UCompany> uCompanyList = uCompanyMapper.selectAllUCompanyList(uCompanyQueryVo);

        return uCompanyList;
    }

    @Override
    public PageInfo<UCompany> selectUCompanyList(UCompanyQueryVo uCompanyQueryVo) {
        PageHelper.startPage(uCompanyQueryVo.getPageNum(), uCompanyQueryVo.getPageSize());
        List<UCompany> uCompanyList = uCompanyMapper.selectAllUCompanyList(uCompanyQueryVo);

        PageInfo<UCompany> uCompanyListInfo = new PageInfo<>(uCompanyList);
        return uCompanyListInfo;
    }

    @Override
    public int queryUCompanyByCode(UCompanyCodeVo uCompanyCodeVo) {
        return uCompanyMapper.queryUCompanyByCode(uCompanyCodeVo);
    }

    @Override
    public int addUCompany(UCompanyAddVo uCompanyAddVo) throws Exception {

        UCompanyWithBLOBs uCompany = new UCompanyWithBLOBs();

        BeanUtils.copyProperties(uCompanyAddVo, uCompany);

        uCompany.setCreatetime(new Date());

        uCompany.setFrtype(1);
        uCompany.setProvincepostage(20d);
        uCompany.setCitypostage(20d);

        int uCompanySize = uCompanyMapper.insertSelective(uCompany);

        if (uCompanySize >= 1) {
            UsersAddVo usersAddVo = new UsersAddVo();
            usersAddVo.setLoginName(uCompany.getCode());
            usersAddVo.setUsertype("2");
            String password = uCompany.getCode();
            usersAddVo.setPassword(Md5Util.encoderByMd5(password));
            usersAddVo.setEmail(uCompany.getEmail());
            usersAddVo.setName(uCompany.getCompanyname());
            usersAddVo.setCompanyid(uCompany.getId());

            USers uSers = new USers();

            BeanUtils.copyProperties(usersAddVo, uSers);

            uSersMapper.insertSelective(uSers);
        }

        return uCompanySize;
    }

    @Override
    public JsonResult updateUCompany(UCompanyUpdateVo uCompanyUpdateVo) {

        UCompanyCodeVo vcode = new UCompanyCodeVo();

        vcode.setCode(uCompanyUpdateVo.getCode());

        //查询之前的记录
        UCompany uCompanyOld = uCompanyMapper.selectByPrimaryKey(uCompanyUpdateVo.getId());

        //如果新的code不等于旧code  则判断是否重名了
        if (!uCompanyOld.getCode().equals(uCompanyUpdateVo.getCode())) {
            //登录名重复
            int count = uCompanyMapper.queryUCompanyByCode(vcode);
            if (count == 1) {
                return JsonResult.build("登录名重复");
            }
        }

        UCompanyWithBLOBs uCompany = uCompanyMapper.selectByPrimaryKey(uCompanyUpdateVo.getId());
        BeanUtils.copyProperties(uCompanyUpdateVo, uCompany);
        int count = uCompanyMapper.updateByPrimaryKeySelective(uCompany);
        if (count < 1) {
            return JsonResult.build("修改失败");
        }

        return JsonResult.ok("修改成功");
    }

    @Override
    public int deleteUCompany(UCompanyDeleteVo uCompanyDeleteVo) {
        UCompanyWithBLOBs uCompany = uCompanyMapper.selectByPrimaryKey(uCompanyDeleteVo.getId());
        //删除/恢复  修改bdelete字段
        if (1 == uCompanyDeleteVo.getBdelete()) {
            uCompany.setBdelete(0);
        } else if (0 == uCompanyDeleteVo.getBdelete()) {
            uCompany.setBdelete(1);
        } else {
            return 0;
        }

        return uCompanyMapper.updateByPrimaryKeySelective(uCompany);
    }


    @Override
    public int addGrandParentId() {
        List<UCompany> list = uCompanyMapper.addGrandParentId();
        int allCount = 0;
        for (UCompany company : list) {
            int id = company.getId();
            UCompanyQueryPlatformVo uCompanyQueryPlatformVo = new UCompanyQueryPlatformVo();
            uCompanyQueryPlatformVo.setParentId(id);
            uCompanyQueryPlatformVo.setCompanyType("20");
            List<UCompany> uCompanyList = uCompanyMapper.selectUCompanyListByParendIdAndCompanyType(uCompanyQueryPlatformVo);

            for (UCompany uCompany : uCompanyList) {
                UCompanyUpdateGrandParentIdVo uCompanyUpdateGrandParentIdVo = new UCompanyUpdateGrandParentIdVo();
                uCompanyUpdateGrandParentIdVo.setParentId(uCompany.getId());
                uCompanyUpdateGrandParentIdVo.setGrandParentId(id);

                uCompanyMapper.updateUCompanyGrandParentId(uCompanyUpdateGrandParentIdVo);
                allCount++;

            }


            //int count = uCompanyMapper.updateUCompanyGrandParentId(uCompanyUpdateGrandParentIdVo);

        }

        return allCount;
    }

    @Override
    public List<UCompany> getAgentList(UCompanyQueryPlatformVo uCompanyQueryPlatformVo) {
        return uCompanyMapper.selectUCompanyListByParendIdAndCompanyType(uCompanyQueryPlatformVo);
    }

    @Override
    public JsonResult getAllAgent() {
        List<UCompany> allAgent = uCompanyMapper.getAllAgent();
        return null;
    }

    /**
     * 10月东莞订单
     *
     * @param
     * @return
     */
    @Override
    public JsonResult getDongguanOrder(DongguanOVo dongguanOVo) {

        List<DongguanOrderQueryVo> list = new ArrayList<>();

        String parentid1 = "1968,";

        String parentid = "1793,1952,1968,2011,1975,2098,2166,2180,2211";

        String a[] = parentid1.split(",");

        List<Map<String, List<DongguanOrderQueryMonthVo>>> all = new ArrayList<>();

        List<DongguanOrderQueryVo> dongguanOrderQueryVoList = new ArrayList<>();

        DongguanOrderVo dongguanOrderVo = new DongguanOrderVo();

        dongguanOrderVo.setParentid(parentid1);

        //查询该代理商下的所有商户
        dongguanOrderQueryVoList = odrOrderMapper.getDongguanOrder(dongguanOrderVo);

        Map<String, List<DongguanOrderQueryMonthVo>> map = new HashMap<>();

        //每个商户月数据

        List<DongguanOrderQueryMonthVo> monthList = new ArrayList<>();

        //获取每一个商户id
        int id = dongguanOVo.getId();

        //获取每一个商户名称
        String companyname = dongguanOVo.getCompanyName();

        //查询每个商户  10月1号到3号的订单
        for (int m = 1; m <= 30; m++) {

            DongguanOrderQueryMonthVo monthVo = new DongguanOrderQueryMonthVo();

            //设置商户id
            dongguanOrderVo.setId(id);

            int as = m;

            if (m <= 8) {
                String st = "2018-10-0" + String.valueOf(as);
                String et = "2018-10-0" + String.valueOf(as + 1);

                Date startDate = DateTools.parseDate(st);
                Date endDate = DateTools.parseDate(et);

                //设置开始结束时间
                dongguanOrderVo.setStartDate(startDate);
                dongguanOrderVo.setEndDate(endDate);

                //查询出数量
                int count = odrOrderMapper.getDongguanOrderCount(dongguanOrderVo);

                //组装数据
                monthVo.setCount(count);
                monthVo.setOrderDate(DateTools.parseDate(et));

                //每个商户三天的数据组
                monthList.add(monthVo);
            }

            if (8 < m && m < 18) {
                String st = "2018-10-1" + String.valueOf(as - 9);
                String et = "2018-10-1" + String.valueOf(as - 8);

                Date startDate = DateTools.parseDate(st);
                Date endDate = DateTools.parseDate(et);

                //设置开始结束时间
                dongguanOrderVo.setStartDate(startDate);
                dongguanOrderVo.setEndDate(endDate);

                //查询出数量
                int count = odrOrderMapper.getDongguanOrderCount(dongguanOrderVo);

                //组装数据
                monthVo.setCount(count);
                monthVo.setOrderDate(DateTools.parseDate(et));

                //每个商户三天的数据组
                monthList.add(monthVo);
            }

            if (m == 18) {
                String st = "2018-10-19";
                String et = "2018-10-20";

                Date startDate = DateTools.parseDate(st);
                Date endDate = DateTools.parseDate(et);

                //设置开始结束时间
                dongguanOrderVo.setStartDate(startDate);
                dongguanOrderVo.setEndDate(endDate);

                //查询出数量
                int count = odrOrderMapper.getDongguanOrderCount(dongguanOrderVo);

                //组装数据
                monthVo.setCount(count);
                monthVo.setOrderDate(DateTools.parseDate(et));

                //每个商户三天的数据组
                monthList.add(monthVo);
            }

            if (18 < m && m < 28) {
                String st = "2018-10-2" + String.valueOf(as - 19);
                String et = "2018-10-2" + String.valueOf(as - 18);

                Date startDate = DateTools.parseDate(st);
                Date endDate = DateTools.parseDate(et);

                //设置开始结束时间
                dongguanOrderVo.setStartDate(startDate);
                dongguanOrderVo.setEndDate(endDate);

                //查询出数量
                int count = odrOrderMapper.getDongguanOrderCount(dongguanOrderVo);

                //组装数据
                monthVo.setCount(count);
                monthVo.setOrderDate(DateTools.parseDate(et));

                //每个商户三天的数据组
                monthList.add(monthVo);
            }

            if (28 == m) {
                String st = "2018-10-29";
                String et = "2018-10-30";

                Date startDate = DateTools.parseDate(st);
                Date endDate = DateTools.parseDate(et);

                //设置开始结束时间
                dongguanOrderVo.setStartDate(startDate);
                dongguanOrderVo.setEndDate(endDate);

                //查询出数量
                int count = odrOrderMapper.getDongguanOrderCount(dongguanOrderVo);

                //组装数据
                monthVo.setCount(count);
                monthVo.setOrderDate(DateTools.parseDate(et));

                //每个商户三天的数据组
                monthList.add(monthVo);
            }


            if (m == 29) {
                String st = "2018-10-30";
                String et = "2018-10-31";

                Date startDate = DateTools.parseDate(st);
                Date endDate = DateTools.parseDate(et);

                //设置开始结束时间
                dongguanOrderVo.setStartDate(startDate);
                dongguanOrderVo.setEndDate(endDate);

                //查询出数量
                int count = odrOrderMapper.getDongguanOrderCount(dongguanOrderVo);

                //组装数据
                monthVo.setCount(count);
                monthVo.setOrderDate(DateTools.parseDate(et));

                //每个商户三天的数据组
                monthList.add(monthVo);
            }

            if (m == 30) {
                String st = "2018-10-31";
                String et = "2018-11-01";

                Date startDate = DateTools.parseDate(st);
                Date endDate = DateTools.parseDate(et);

                //设置开始结束时间
                dongguanOrderVo.setStartDate(startDate);
                dongguanOrderVo.setEndDate(endDate);

                //查询出数量
                int count = odrOrderMapper.getDongguanOrderCount(dongguanOrderVo);

                //组装数据
                monthVo.setCount(count);
                monthVo.setOrderDate(DateTools.parseDate(et));

                //每个商户三天的数据组
                monthList.add(monthVo);
            }

        }

        map.put(companyname, monthList);

        return JsonResult.ok(map);
    }

    /**
     * @param code 微信用户code
     * @author XOu
     * @description 获取微信用户信息
     * @version 1.0
     * @date 2018/7/1
     * @modified
     */
    public Map<String, String> getWxUserInfo(String code) {
        String openParam = "appid=" + WxConfigUtil.JKDL_BUSINESS_APPID + "&secret=" + WxConfigUtil.JKDL_BUSINESS_SECRT + "&js_code=" + code + "&grant_type=authorization_code";
        String openJsonStr = HttpUtil.SendGET("https://api.weixin.qq.com/sns/jscode2session", openParam);
        log.info("获取微信用户unionId接口返回参数{}", openJsonStr);

        Map openMap = JSON.parseObject(openJsonStr);
        if (openMap.containsKey("errcode")) {
            log.error("==========调用微信接口异常{}", String.valueOf(openMap.get("errmsg")));
            throw new BusinessException("调用微信接口异常");
        }
        log.info("获取的openid是", openMap.get("openid"));
        String sessionKey = String.valueOf(openMap.get("session_key"));
        String openid = String.valueOf(openMap.get("openid"));
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("sessionKey", sessionKey);
        resultMap.put("openid", openid);
        return resultMap;
    }

    @Override
    public Map<String, Object>checkoutUCompanyExist(String code) {
        Map<String, String> userInfo = getWxUserInfo(code);
        if (null == userInfo || userInfo.isEmpty()) {
            throw new BusinessException("用户信息查询失败");
        }
        UCompany uCompany = uCompanyMapper.selectByOpenid(userInfo.get("openid"));
        Map<String, Object> result = new HashMap<>();
        if (null!=uCompany && null!=uCompany.getOpenid()) {
            result.put("isExist", 1);
            result.put("wxUserId", uCompany.getId());
            result.put("openid",userInfo.get("openid"));
            return result;
        } else {
            UCompanyUser uCompanyUser = uCompanyUserMapper.selectByOpenId(userInfo.get("openid"));
            if (null!=uCompanyUser && null!=uCompanyUser.getOpenid()) {
                result.put("isExist", 2);
                result.put("wxUserId", uCompanyUser.getCompanyId());
                result.put("wxTowUserId", uCompanyUser.getId());
                result.put("openid",userInfo.get("openid"));
                return result;
            }
            result.put("isExist", 0);
            result.put("wxUserId", null);
            result.put("openid",userInfo.get("openid"));

            return result;
        }

    }

    @Override
    public int loginAuth(UsersWxVo usersWxVo) throws Exception {

        return 0;
    }

    @Override
    public JsonResult addUCompanyOpenid(UsersWxVo usersWxVo) {
        SystemLoginVo systemLoginVo = new SystemLoginVo();
        systemLoginVo.setLoginName(usersWxVo.getLoginName());
        systemLoginVo.setPassword(usersWxVo.getPassword());
        int id = systemUserRoleAuthService.systemLogin(systemLoginVo);
        int towId = systemUserRoleAuthService.systemUserLogin(systemLoginVo);
        if(id == 0 && towId == 0) {
            return JsonResult.build("登录失败");
        }
        UsersIdStatusVo usersIdStatusVo = new UsersIdStatusVo();
        if(id != 0){
            USers uSers = uSersMapper.selectByPrimaryKey(id);

            UCompany uCompany = uCompanyMapper.selectByPrimaryKey(uSers.getCompanyid());
            uCompany.setOpenid(usersWxVo.getOpenid());
            String string = EmojiParser.removeAllEmojis(usersWxVo.getNickname());
            uCompany.setNickname(string);
            uCompany.setAvatarUrl(usersWxVo.getHeadimgurl());
            int updateUCompany = uCompanyMapper.updateByPrimaryKey(uCompany);
            usersIdStatusVo.setWxUserId(uSers.getCompanyid());
            usersIdStatusVo.setId(updateUCompany);
        }else{
            UCompanyUser uCompanyUser = uCompanyUserMapper.selectById(towId);
            uCompanyUser.setOpenid(usersWxVo.getOpenid());
            String string = EmojiParser.removeAllEmojis(usersWxVo.getNickname());
            uCompanyUser.setNickname(string);
            uCompanyUser.setAvatarurl(usersWxVo.getHeadimgurl());
            int updateUCompany = uCompanyUserMapper.updateByPrimaryKeySelective(uCompanyUser);
            usersIdStatusVo.setWxUserId(uCompanyUser.getCompanyId());
            usersIdStatusVo.setId(updateUCompany+1);
            usersIdStatusVo.setWxTowUserId(towId);
        }
        return JsonResult.ok(usersIdStatusVo);
    }

    @Override
    public List<UCompany> getAgencyCompanyList(CloseAnAccountVo closeAnAccountVo) {
        return uCompanyMapper.getAgencyCompanyList(closeAnAccountVo);
    }

    /**
     * 获取结算列表
     */
    @Override
    public List<SettleAccounts> getJiesuanList(CloseAnAccountVo closeAnAccountVo) {


        //获取到公司表---公司名称--充电金额--公司ID
        List<UCompany> uCompanyListInfo = uCompanyMapper.getAgencyCompanyList(closeAnAccountVo);
        //获取到设备表--设备数量--公司ID
        List<PdProducts> pdProductsInfo = pdProductsMapper.getmachineCount(closeAnAccountVo);
        //获取到订单表--价格  1 or 2 or 3-  订单数
        List<OdrOrder> odrOrderListInfo = odrOrderMapper.orderInfoList(closeAnAccountVo);
        //查询出公司订单开始日期 到最后日期
        List<OdrOrder> odrOrderDateInfo = odrOrderMapper.orderDateInfoList();
        //创建新的工具实体list
        List<SettleAccounts> closeanaccountList = new ArrayList<>();

        //需要的数据存入
        for (int i = 0; i < uCompanyListInfo.size(); i++) {
            SettleAccounts settleAccounts = new SettleAccounts();
            for (int j = 0; j < pdProductsInfo.size(); j++) {
//                if (null != pdProductsInfo.get(j)) {
//                    if (null != pdProductsInfo.get(j).getCompanyid()) {
//
//                        int companyId = pdProductsInfo.get(j).getCompanyid();
//
//                        int uCompanyId = uCompanyListInfo.get(i).getId();
//
//                        if (companyId == uCompanyId) {
//                            //公司名称
//                            settleAccounts.setCompanyname(uCompanyListInfo.get(i).getCompanyname());
//                            //充电金额
//                            settleAccounts.setNationpostage(uCompanyListInfo.get(i).getNationpostage());
//                            //商户创建时间
//                            settleAccounts.setCreatetime(uCompanyListInfo.get(i).getCreatetime());
//                            //设备数量
//                            settleAccounts.setMachineCount(pdProductsInfo.get(j).getMachineCount());
//                        }
//                    }
//                }
                settleAccounts.setCompanyname(uCompanyListInfo.get(i).getCompanyname());
                //充电金额
                settleAccounts.setNationpostage(uCompanyListInfo.get(i).getNationpostage());
                //商户创建时间
                settleAccounts.setCreatetime(uCompanyListInfo.get(i).getCreatetime());
                //设备数量
                if(null == uCompanyListInfo.get(i).getDevicenumber() || 0 == uCompanyListInfo.get(i).getDevicenumber()){
                    settleAccounts.setMachineCount(1);
                }else{
                    settleAccounts.setMachineCount(uCompanyListInfo.get(i).getDevicenumber() );
                }

            }
            for (int z = 0; z < odrOrderListInfo.size(); z++) {
                if (odrOrderListInfo.get(z).getQyid().equals(uCompanyListInfo.get(i).getId())) {

                    settleAccounts.setBeginDate(odrOrderListInfo.get(z).getCreatedate()); //最小时间
                    settleAccounts.setEndDate(odrOrderListInfo.get(z).getMaxcreatedate());//最大时间

                    if (odrOrderListInfo.get(z).getPayamount().intValue() == 1) {
                        //1元订单数
                        settleAccounts.setOne(odrOrderListInfo.get(z).getOrderCount());
                    }
                    if (odrOrderListInfo.get(z).getPayamount().intValue() == 2) {
                        //2元订单数
                        settleAccounts.setToo(odrOrderListInfo.get(z).getOrderCount());
                    }
                    if (odrOrderListInfo.get(z).getPayamount().intValue() == 3) {
                        //3元订单数
                        settleAccounts.setThree(odrOrderListInfo.get(z).getOrderCount());
                    }

                    if (odrOrderListInfo.get(z).getPayamount().intValue() == 4) {
                        //4元订单数
                        settleAccounts.setFour(odrOrderListInfo.get(z).getOrderCount());
                    }
                    if (odrOrderListInfo.get(z).getPayamount().intValue() == 5) {
                        //5元订单数
                        settleAccounts.setFive(odrOrderListInfo.get(z).getOrderCount());
                    }

                    if (odrOrderListInfo.get(z).getPayamount().intValue() == 0.01) {
                        //0.01元订单数
                        settleAccounts.setZeroOne(odrOrderListInfo.get(z).getOrderCount());
                    }

                }
            }
            for (int x = 0; x < odrOrderDateInfo.size(); x++) {
                if (uCompanyListInfo.get(i).getId().equals(odrOrderDateInfo.get(x).getQyid())) {
                    settleAccounts.setBeginDate(odrOrderDateInfo.get(x).getCreatedate());
                    settleAccounts.setEndDate(odrOrderDateInfo.get(x).getMaxcreatedate());
                }
            }
            if (null != settleAccounts.getCompanyname()) {
                if (null != closeAnAccountVo.getStartDate() && null != closeAnAccountVo.getEndDate()) {
                    settleAccounts.setBeginDate(closeAnAccountVo.getStartDate());
                    settleAccounts.setEndDate(closeAnAccountVo.getEndDate());


                }
                if (null == settleAccounts.getOne()) {
                    settleAccounts.setOne(0);
                }
                if (null == settleAccounts.getToo()) {
                    settleAccounts.setToo(0);
                }
                if (null == settleAccounts.getThree()) {
                    settleAccounts.setThree(0);
                }
                if (null == settleAccounts.getFour()) {
                    settleAccounts.setFour(0);
                }
                if (null == settleAccounts.getFive()) {
                    settleAccounts.setFive(0);
                }
                if (null == settleAccounts.getZeroOne()) {
                    settleAccounts.setZeroOne(0);
                }

                //充电金额
                int CdianMoney = settleAccounts.getNationpostage().intValue();
                //设备数量
                int machineCount = settleAccounts.getMachineCount();
                //交易笔数
                //int sumCount = settleAccounts.getZeroOne() + settleAccounts.getOne() + settleAccounts.getToo() + settleAccounts.getThree() + settleAccounts.getFive();
                int sumCount =  settleAccounts.getOne() + settleAccounts.getToo() + settleAccounts.getThree() + settleAccounts.getFour() + settleAccounts.getFive();
                //总金额

                double totalmoney = 0d;
                totalmoney =  settleAccounts.getOne()+settleAccounts.getToo()*2+settleAccounts.getThree()*3+settleAccounts.getFour()*4+settleAccounts.getFive()*5;

                //int totalmoney = sumCount * settleAccounts.getNationpostage().intValue();

                //月均使用次数
                double yavg = (double) sumCount / machineCount;
                //平台服务费
                double servicecharge = 0;
                //商户创建时间
                Date companycreatedate = settleAccounts.getCreatetime();
                //每台月营业额
                double countavg = (double) totalmoney / machineCount;
                //客诉服务费
                double aftersaleService = machineCount * 0.2;
                if (yavg < 4) {
                    servicecharge = 0;
                } else {
                    if (yavg > 4 && yavg < 5) {
                        if (2 == CdianMoney) {
                            servicecharge = 0.5 * machineCount;
                        }
                        if (3 == CdianMoney) {
                            servicecharge = 1.0 * machineCount;
                        }
                    }
                    if (yavg > 5 && yavg < 11) {
                        if (2 == CdianMoney) {
                            servicecharge = 0.8 * machineCount;
                        }
                        if (3 == CdianMoney) {
                            servicecharge = 1.3 * machineCount;
                        }
                    }
                    if (yavg > 11) {
                        if (2 == CdianMoney) {
                            servicecharge = 1.0 * machineCount;
                        }
                        if (3 == CdianMoney) {
                            servicecharge = 1.5 * machineCount;
                        }

                    }

                }

                //平台服务费保留两位小数
                BigDecimal servicechargenew = new BigDecimal(servicecharge);
                servicecharge = servicechargenew.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                //客诉服务费保留两位小数
                BigDecimal aftersaleServicenew = new BigDecimal(aftersaleService);
                aftersaleService = aftersaleServicenew.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                //每台营业额保留两位小数
                BigDecimal countavgnew = new BigDecimal(countavg);
                countavg = countavgnew.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                //月均使用次数保留两位小数
                BigDecimal yavgnew = new BigDecimal(yavg);
                yavg = yavgnew.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                settleAccounts.setTransactionNumber(sumCount);
                settleAccounts.setTotalSum(totalmoney);
                settleAccounts.setMonthAvg(yavg);
                settleAccounts.setServiceCost(servicecharge);
                settleAccounts.setAftersaleService(aftersaleService);
                settleAccounts.setCountavg(countavg);
                closeanaccountList.add(settleAccounts);

            }
        }

        //PageInfo<SettleAccounts> settleAccountsListInfo = new PageInfo<>(closeanaccountList);
        return closeanaccountList;
    }

    //结算数据导出
    @Override
    public HSSFWorkbook exportJiesuan(CloseAnAccountVo closeAnAccountVo,HttpServletResponse response) throws ParseException {

        List<SettleAccounts> closeanaccountList =getJiesuanList(closeAnAccountVo);
        DateTools dateTools = new DateTools();
//1.创建Excel文档
        HSSFWorkbook workbook = null;
        try {
            workbook = new HSSFWorkbook();
            //2.创建文档摘要
            workbook.createInformationProperties();
            //3.获取文档信息，并配置
            DocumentSummaryInformation dsi = workbook.getDocumentSummaryInformation();
            //3.1文档类别
            dsi.setCategory("结算详情");
            //3.2设置文档管理员
            dsi.setManager("");
            //3.3设置组织机构
            dsi.setCompany("");
            //4.获取摘要信息并配置
            SummaryInformation si = workbook.getSummaryInformation();
            //4.1设置文档主题
            si.setSubject("结算详情");
            //4.2.设置文档标题
            si.setTitle("结算详情");
            //4.3 设置文档作者
            si.setAuthor("");
            //4.4设置文档备注
            si.setComments("备注信息暂无");
            //创建Excel表单
            HSSFSheet sheet = workbook.createSheet("商户");
            //创建日期显示格式
            HSSFCellStyle dateCellStyle = workbook.createCellStyle();
            dateCellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
            //创建标题的显示样式
            HSSFCellStyle headerStyle = workbook.createCellStyle();
            headerStyle.setAlignment(HorizontalAlignment.CENTER);
            headerStyle.setFillForegroundColor(IndexedColors.YELLOW.index);
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            //定义列的宽度
            sheet.setColumnWidth(0, 14 * 256);
            sheet.setColumnWidth(1, 10 * 256);
            sheet.setColumnWidth(2, 10 * 256);
            sheet.setColumnWidth(3, 10 * 256);
            sheet.setColumnWidth(4, 20 * 256);
            sheet.setColumnWidth(5, 10 * 256);
            sheet.setColumnWidth(6, 10 * 256);
            sheet.setColumnWidth(7, 10 * 256);
            sheet.setColumnWidth(8, 16 * 256);
            sheet.setColumnWidth(9, 16 * 256);
            sheet.setColumnWidth(10, 25 * 256);
            sheet.setColumnWidth(11, 20 * 256);
            sheet.setColumnWidth(12, 18 * 256);
            sheet.setColumnWidth(13, 20 * 256);
            sheet.setColumnWidth(14, 20 * 256);
            sheet.setColumnWidth(15, 20 * 256);

            //5.设置表头
            HSSFRow headerRow = sheet.createRow(0);
            HSSFCell cell0 = headerRow.createCell(0);
            cell0.setCellValue("开始时间");
            cell0.setCellStyle(headerStyle);
            HSSFCell cell1 = headerRow.createCell(1);
            cell1.setCellValue("结束时间");
            cell1.setCellStyle(headerStyle);
            HSSFCell cell2 = headerRow.createCell(2);
            cell2.setCellValue("公司名称");
            cell2.setCellStyle(headerStyle);
            HSSFCell cell3 = headerRow.createCell(3);
            cell3.setCellValue("设备数量");
            cell3.setCellStyle(headerStyle);
            HSSFCell cell4 = headerRow.createCell(4);
            cell4.setCellValue("充电金额");
            cell4.setCellStyle(headerStyle);
            HSSFCell cell5 = headerRow.createCell(5);
            cell5.setCellValue("1元订单数");
            cell5.setCellStyle(headerStyle);
            HSSFCell cell6 = headerRow.createCell(6);
            cell6.setCellValue("2元订单数");
            cell6.setCellStyle(headerStyle);
            HSSFCell cell7 = headerRow.createCell(7);
            cell7.setCellValue("3元订单数");
            cell7.setCellStyle(headerStyle);
            HSSFCell cell8 = headerRow.createCell(8);
            cell8.setCellValue("5元订单数");
            cell8.setCellStyle(headerStyle);

            HSSFCell cell10 = headerRow.createCell(9);
            cell10.setCellValue("交易笔数");
            cell10.setCellStyle(headerStyle);
            HSSFCell cell11 = headerRow.createCell(10);
            cell11.setCellValue("平均使用次数");
            cell11.setCellStyle(headerStyle);
            HSSFCell cell12 = headerRow.createCell(11);
            cell12.setCellValue("总金额");
            cell12.setCellStyle(headerStyle);
            HSSFCell cell13 = headerRow.createCell(12);
            cell13.setCellValue("平台服务费");
            cell13.setCellStyle(headerStyle);
            HSSFCell cell9 = headerRow.createCell(13);
            cell9.setCellValue("客诉服务费");
            cell9.setCellStyle(headerStyle);
            HSSFCell cel20 = headerRow.createCell(14);
            cel20.setCellValue("每台营业额");
            cel20.setCellStyle(headerStyle);
            HSSFCell cel21 = headerRow.createCell(15);
            cel21.setCellValue("商户创建时间");
            cel21.setCellStyle(headerStyle);

            //6.装数据
            for (int i = 0; i < closeanaccountList.size(); i++) {
                HSSFRow row = sheet.createRow(i + 1);
                SettleAccounts data = closeanaccountList.get(i);

                row.createCell(0).setCellValue(dateTools.format(data.getBeginDate(),"yyyy-MM-dd HH:mm:ss"));
                row.createCell(1).setCellValue(dateTools.format(data.getEndDate(),"yyyy-MM-dd HH:mm:ss"));
                row.createCell(2).setCellValue(data.getCompanyname());
                row.createCell(3).setCellValue(data.getMachineCount());
                row.createCell(4).setCellValue(data.getNationpostage());
                row.createCell(5).setCellValue(data.getOne());
                row.createCell(6).setCellValue(data.getToo());
                row.createCell(7).setCellValue(data.getThree());
                row.createCell(8).setCellValue(data.getFive());
                row.createCell(9).setCellValue(data.getTransactionNumber());
                row.createCell(10).setCellValue(data.getMonthAvg());
                row.createCell(11).setCellValue(data.getTotalSum());
                row.createCell(12).setCellValue(data.getServiceCost());
                row.createCell(13).setCellValue(data.getAftersaleService());
                row.createCell(14).setCellValue(data.getCountavg());
                row.createCell(15).setCellValue(dateTools.format(data.getCreatetime(),"yyyy-MM-dd HH:mm:ss"));

            }


            String fileName = "导出结算excel.xls";

            //生成excel文件
            buildExcelFile(fileName, workbook);

            //浏览器下载excel
            buildExcelDocument(fileName, workbook, response);

            return null;

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public UCompany getUCompany(int id) {
        return uCompanyMapper.selectByPrimaryKey(id);
    }

    //生成excel文件
    protected void buildExcelFile(String filename,HSSFWorkbook workbook) throws Exception{
        FileOutputStream fos = new FileOutputStream(filename);
        workbook.write(fos);
        fos.flush();
        fos.close();

    }

    //浏览器下载excel
    protected void   buildExcelDocument(String filename,HSSFWorkbook workbook,HttpServletResponse response) throws Exception{
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(filename, "utf-8"));
        OutputStream outputStream = null;
        try {
            outputStream= response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        }catch (Exception e){
            throw e;
        }
        finally {
            outputStream.close();
        }

    }

  //获取公司名
    @Override
    public String getCompanyName(OdrOrderdetailReportdatailVo odrOrderdetailReportdatailVo){
        return uCompanyMapper.getCompanyName(odrOrderdetailReportdatailVo);
    }


    /**
     * 通过商户名获取设备数量
     */

    //获取公司名3
    @Override
    public  int getProductCountByName(PdProductCountQueryVo pdProductCountQueryVo){
        return uCompanyMapper.getProductCountByName(pdProductCountQueryVo);
    }

    @Override
    public JsonResult quitXcxLogin(UsersIdVo usersIdVo) {

        int updateUCompany = uCompanyMapper.updateByXcxOpeeid(usersIdVo);
        if(updateUCompany == 0){
            return JsonResult.build("退出失败");
        }
        return JsonResult.ok(updateUCompany);

    }
}








